#include "InternetClient.h"


internetClient::internetClient(const QString &hostName, quint16 port)
{
    C_connect(hostName, port);
}

bool internetClient::C_connect(const QString &hostName, quint16 port)
{
    arg = false;
    // 连接到服务器
    socket.connectToHost(hostName, port);
    if (socket.waitForConnected()) {
        arg = true;
        qDebug() << "Data sent successfully.";
        return true;
    }
    else
    {
        qDebug() << "Failed to connect to server: " << socket.errorString();
        return false;
    }
}

void internetClient::C_send()
{
    if(arg == true)
    {
        qDebug() << "连接成功";
        // 准备要发送的数据
        database d;
        d.temperature = QRandomGenerator::global()->bounded(100,100000)/1000.0;
        d.humidity = QRandomGenerator::global()->bounded(100,100000)/1000.0;
        d.dust_density = QRandomGenerator::global()->bounded(100,100000)/1000.0;
        d.MFS = QRandomGenerator::global()->bounded(100,100000)/1000.0;
        QByteArray byteArray;
        byteArray.resize(sizeof(database));
        memcpy(byteArray.data(), &d, sizeof(database));
        socket.write(byteArray);
        socket.waitForBytesWritten();
        qDebug() << "Data sent successfully.";
    }
}
